package com.newtouch.bxzs.common.base.util;

import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件格式检验工具类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/2/24 17:28</td>
 * <td>dingqianbin</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author dingqianbin
 * @version 1.0.0
 * @since 1.0.0
 */
public class FileFormatUtil {

	private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);

	/** 校验文件格式正则表达式，包含对jpg|png|jpeg|bmp|mp4|rmvb|wma|avi|pdf的校验 */
	private static final String FILE_CHECK_RULE = "^.*?\\.(jpg|png|jpeg|bmp|mp4|rmvb|wma|avi|pdf)$";

	/**
	 * 单个文件校验格式
	 *
	 * @param file
	 *            MultipartFile
	 */
	public static void fileFormatCheck(MultipartFile file) {
		if (StringUtils.isEmpty(file.getOriginalFilename())) {
			logger.error("文件名称为空！");
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (!file.getOriginalFilename().matches(FILE_CHECK_RULE)) {
			logger.error("文件格式错误！");
			throw new BaseException(BaseErrorEnum.FILE_FORMAT_ERROR);
		}
	}

	/**
	 * 多个文件校验格式
	 *
	 * @param files
	 *            MultipartFile集合
	 */
	public static void filesFormatCheck(List<MultipartFile> files) {
		for (MultipartFile file : files) {
			if (StringUtils.isEmpty(file.getOriginalFilename())) {
				logger.error("文件名称为空！");
				throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
			}
			if (!file.getOriginalFilename().toLowerCase().matches(FILE_CHECK_RULE)) {
				logger.error("文件格式错误！");
				throw new BaseException(BaseErrorEnum.FILE_FORMAT_ERROR);
			}
		}

	}

}
